package com.jinhuhang.u2.myselfmodule.engine.bid;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.jinhuhang.u2.MyApplication;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.api.RetrofitUtils;
import com.jinhuhang.u2.common.constant.Constant;
import com.jinhuhang.u2.common.mvp.activity.ZSimpleBaseActivity;
import com.jinhuhang.u2.entity.AccountBean;
import com.jinhuhang.u2.entity.BidBean;
import com.jinhuhang.u2.entity.UserSingleResult;
import com.jinhuhang.u2.listener.Listener;
import com.jinhuhang.u2.myselfmodule.adapter.BidAdapter;
import com.jinhuhang.u2.myselfmodule.engine.bid.addbid.AddBidActivity;
import com.jinhuhang.u2.myselfmodule.engine.bid.tips.BidTipsActivity;
import com.jinhuhang.u2.ui.customview.MutipleLayout;
import com.jinhuhang.u2.util.UtilsCollection;
import com.jinhuhang.u2.util.http.HttpWrapperList;
import com.jinhuhang.u2.util.http.ResultList;
import com.jinhuhang.u2.util.http.T;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by OnionMac on 17/9/18.
 */

public class BidActivity extends ZSimpleBaseActivity {

    @Bind(R.id.toolbar_back)
    ImageView mToolbarBack;
    @Bind(R.id.toolbar_name)
    TextView mToolbarName;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.bid_tips)
    TextView mBidTips;
    @Bind(R.id.bid_recy)
    RecyclerView mBidRecy;
    @Bind(R.id.bid_addbid)
    ImageView mBidAddbid;
    @Bind(R.id.bid_muti)
    MutipleLayout mMutipleLayout;
    private BidAdapter mBidAdapter;
    private List<BidBean> mDatas;

    public static final int ADD = 101;
    public static final int CHANGE = 102;
    public static final String TYPE = "type";
    public static final String DATA = "data";

    private static final String OPEN = "0";
    private static final String CLOSE = "1";

    @Override
    protected void initView() {
        mToolbarBack.setOnClickListener(v -> finish());
        mToolbarName.setText("自动投标");

        mDatas = new ArrayList<>();
        mBidRecy.setLayoutManager(new LinearLayoutManager(this));
        mBidAdapter = new BidAdapter(R.layout.item_bid_view, mDatas);
        mBidAdapter.bindToRecyclerView(mBidRecy);
        mBidRecy.setAdapter(mBidAdapter);
        mMutipleLayout.setEmptyText("您当前暂无自动投标记录!");
        mMutipleLayout.setEmptyImage(R.drawable.account_zanwujiaoyijilu);
        mMutipleLayout.setEmptyBottomText("※ 市场有风险,出借需谨慎");
        mMutipleLayout.setEmptyBottomTextVisiable(true);
        mMutipleLayout.setOnReloadListener(v -> {
            initData();
        });
    }

    @Override
    protected void initData() {
        mMutipleLayout.setStatus(MutipleLayout.Loading);
        getBidList();
    }

    /**
     * 拿到Bid自动投标列表
     */
    private void getBidList() {
        addSubscription(RetrofitUtils.getInstance().build()
                .getBidList(getUserId())
                .compose(T.D())
                .subscribe(new ResultList<HttpWrapperList<BidBean>>() {
                    @Override
                    protected void onSuccess(HttpWrapperList<BidBean> o) {
                        if (o.data != null && o.data.size() > 0) {
                            mMutipleLayout.setStatus(MutipleLayout.Success);
                            mBidAdapter.addData(o.data);
                        } else {
                            mMutipleLayout.setStatus(MutipleLayout.Empty);
                        }
                    }

                    @Override
                    protected void onFaild() {
                        mMutipleLayout.setStatus(MutipleLayout.Error);
                    }
                }));
    }

    @Override
    protected void initListener() {
        mBidAddbid.setOnClickListener(v -> {
            if (mDatas.size() > 2) {
                showMessage("最多可添加三条规则,请先删除一条");
            } else {
                Intent intent = new Intent(this, AddBidActivity.class);
                intent.putExtra(TYPE, ADD);
                startActivityForResult(intent, ADD);
            }
        });

        mBidAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.item_bid_delete:
                    UtilsCollection.getSlectDialog(this, "提示", "确定要删除这条自动投标规则吗?", "取消", "确定", new Listener.OnNormalAlertDialogChooseClickListener() {
                        @Override
                        public void onLeft() {

                        }

                        @Override
                        public void onRight() {
                            delete(position);
                        }
                    }).show();
                    break;
                case R.id.item_bid_change:
                    UtilsCollection.getSlectDialog(this, "提示", "是否要修改这条自动投标规则?", "我点错了", "修改", new Listener.OnNormalAlertDialogChooseClickListener() {
                        @Override
                        public void onLeft() {

                        }

                        @Override
                        public void onRight() {
                            change(position);
                        }
                    }).show();
                    break;
                case R.id.item_bid_cb:
                    CheckBox cb = (CheckBox) adapter.getViewByPosition(position, R.id.item_bid_cb);
                    status(cb.isChecked(), mDatas.get(position), position);
                    break;
            }
        });

        mBidTips.setOnClickListener(v -> {
            startActivity(new Intent(this, BidTipsActivity.class));
        });
    }

    private void status(boolean isChecked, BidBean bidBean, int position) {
        /**
         * 不能开启两条
         */
        for (int i = 0; i < mDatas.size(); i++) {
            if (i != position && OPEN.equals(mDatas.get(i).getStatus())) {
                mBidAdapter.notifyDataSetChanged();
                UtilsCollection.getSingleDialog(this, "提示", "已经有一条自动投标规则开启,请先关闭这条规则", "确定", () -> {
                }).show();
                return;
            }
        }
        showDialog(UtilsCollection.connectString("正在", isChecked ? "开启" : "关闭", "自动投标"));
        addSubscription(RetrofitUtils.getInstance().build()
                .changeBidStatus(getUserId(), bidBean.getId(), isChecked ? OPEN : CLOSE)
                .compose(T.D())
                .subscribe(new ResultList<HttpWrapperList<UserSingleResult>>() {
                    @Override
                    protected void onSuccess(HttpWrapperList<UserSingleResult> o) {
                        if (Constant.SUCCESS_CODE == o.code) {
                            bidBean.setStatus(isChecked ? OPEN : CLOSE);
                            mBidAdapter.notifyDataSetChanged();
                        } else {
                            showMessage(o.getInfo());
                        }
                    }

                    @Override
                    protected void onFinish() {
                        dissDialog();
                    }
                }));
    }

    /**
     * 修改
     *
     * @param position
     */
    private void change(int position) {
        BidBean bidBean = mDatas.get(position);
        Intent intent = new Intent(this, AddBidActivity.class);
        intent.putExtra(TYPE, CHANGE);
        intent.putExtra(DATA, MyApplication.mGson.toJson(bidBean));
        startActivityForResult(intent, CHANGE);
    }

    /**
     * 删除
     *
     * @param position
     */
    private void delete(int position) {
        BidBean bidBean = mDatas.get(position);
        showDialog("删除投标规则");
        addSubscription(RetrofitUtils.getInstance().build()
                .deleteBid(getUserId(), bidBean.getId())
                .compose(T.D())
                .subscribe(new ResultList<HttpWrapperList<UserSingleResult>>() {
                    @Override
                    protected void onSuccess(HttpWrapperList<UserSingleResult> o) {
                        if (Constant.SUCCESS_CODE == o.code) {
                            mDatas.remove(position);
                            /**
                             * 删除完发现没有投标规则
                             */
                            if (mDatas.size() == 0) {
                                mMutipleLayout.setStatus(MutipleLayout.Empty);
                            }
                            mBidAdapter.notifyDataSetChanged();
                            showMessage("删除成功");
                        } else {
                            showMessage(o.getInfo());
                        }
                    }

                    @Override
                    protected void onFinish() {
                        dissDialog();
                    }
                }));
    }

    @Override
    protected void attachPre() {

    }

    @Override
    public void destory() {
        super.destory();

        AccountBean account = MyApplication.mSpUtil.getAccount();

        if(mDatas == null || mDatas.size() == 0){
            account.setAotuType(0);
        }else{
            boolean have = false;
            for (BidBean data : mDatas) {
                if("0".equals(data.getStatus())){
                    have = true;
                }
            }
            account.setAotuType(have?2:1);
        }
        MyApplication.mSpUtil.setAccount(account);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bid;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        initData();
        mDatas.clear();
    }
}
